﻿using System.Collections.Generic;
using System.IO;
using Compass.Wasm.Shared.Categories;
using Compass.Wasm.Shared.Extensions;
using Application = Microsoft.Office.Interop.Excel.Application;

namespace Compass.Wpf.ViewModels.Settings;

public class MaterialItemsViewModel : NavigationViewModel
{
    #region ctor
    private readonly IMaterialItemService _materialItemService;
    public MaterialItemsViewModel(IContainerProvider provider) : base(provider)
    {
        _materialItemService = provider.Resolve<IMaterialItemService>();

        MaterialItemDto = new MaterialItemDto();
        AddMaterialItemCommand = new DelegateCommand(AddMaterialItem);
        UpdateMaterialItemCommand = new DelegateCommand<MaterialItemDto>(UpdateMaterialItem);
        DeleteMaterialItemCommand = new DelegateCommand<MaterialItemDto>(DeleteMaterialItem);
        SaveMaterialItemCommand = new DelegateCommand(SaveMaterialItem);

        OpenCsvCommand = new DelegateCommand(OpenCsv);
        UpdateCommand = new DelegateCommand(Update);
        UpdateRoles = "admin";
    }

    private string updateRoles;
    public string UpdateRoles
    {
        get => updateRoles;
        set { updateRoles = value; RaisePropertyChanged(); }
    }


    public DelegateCommand AddMaterialItemCommand { get; }
    public DelegateCommand<MaterialItemDto> UpdateMaterialItemCommand { get; }
    public DelegateCommand<MaterialItemDto> DeleteMaterialItemCommand { get; }
    public DelegateCommand SaveMaterialItemCommand { get; }

    public DelegateCommand OpenCsvCommand { get; }
    public DelegateCommand UpdateCommand { get; }
    #endregion

    #region 右侧展开栏属性
    private bool isRightDrawerOpen;
    /// <summary>
    /// 右侧窗口是否展开
    /// </summary>
    public bool IsRightDrawerOpen
    {
        get => isRightDrawerOpen;
        set { isRightDrawerOpen = value; RaisePropertyChanged(); }
    }
    private string rightDrawerTitle = null!;
    public string RightDrawerTitle
    {
        get => rightDrawerTitle;
        set { rightDrawerTitle = value; RaisePropertyChanged(); }
    }

    #endregion

    #region 属性
    private string[] units = null!;
    public string[] Units
    {
        get => units;
        set { units = value; RaisePropertyChanged(); }
    }
    private string[] hoodGroups = null!;
    public string[] HoodGroups
    {
        get => hoodGroups;
        set { hoodGroups = value; RaisePropertyChanged(); }
    }
    private string[] ceilingGroups = null!;
    public string[] CeilingGroups
    {
        get => ceilingGroups;
        set { ceilingGroups = value; RaisePropertyChanged(); }
    }
    private string[] ceilingRules = null!;
    public string[] CeilingRules
    {
        get => ceilingRules;
        set { ceilingRules = value; RaisePropertyChanged(); }
    }
    private string search;
    /// <summary>
    /// 搜索条件属性
    /// </summary>
    public string Search
    {
        get => search;
        set
        {
            search = value; RaisePropertyChanged();
            Filter();
        }
    }

    private MaterialItemDto materialItemDto;
    public MaterialItemDto MaterialItemDto
    {
        get => materialItemDto;
        set { materialItemDto = value; RaisePropertyChanged(); }
    }
    public ObservableRangeCollection<MaterialItemDto> MaterialItemDtos { get; } = new();
    public ObservableRangeCollection<MaterialItemDto> FilterMaterialItemDtos { get; } = new();



    #endregion

    #region 增删改查
    private void AddMaterialItem()
    {
        MaterialItemDto = new MaterialItemDto();

        IsRightDrawerOpen = true;
        RightDrawerTitle = "添加设计物料";
    }

    private void UpdateMaterialItem(MaterialItemDto obj)
    {
        MaterialItemDto = obj;

        IsRightDrawerOpen = true;
        RightDrawerTitle = "修改设计物料";
    }

    private async void DeleteMaterialItem(MaterialItemDto obj)
    {
        //删除询问
        var dialogResult = await DialogHost.Question("删除确认", $"确认删除设计物料：{obj.MtlNumber}, {obj.Description} 吗?");
        if (dialogResult.Result != ButtonResult.OK) return;
        await _materialItemService.DeleteAsync(obj.Id.Value);
        GetDataAsync();
    }

    private async void SaveMaterialItem()
    {
        //数据验证
        if (string.IsNullOrWhiteSpace(MaterialItemDto.MtlNumber))
        {
            //发送提示
            Aggregator.SendMessage("物料编号不能为空");
            return;
        }
        if (string.IsNullOrWhiteSpace(MaterialItemDto.MtlNumber))
        {
            //发送提示
            Aggregator.SendMessage("类型不能为空，默认写配件");
            return;
        }

        try
        {
            MaterialItemDto.MtlNumber =MaterialItemDto.MtlNumber.ToUpper();
            MaterialItemDto.Type =MaterialItemDto.Type.ToUpper();
            if (MaterialItemDto.Id != null && MaterialItemDto.Id.Value != Guid.Empty)
            {
                await _materialItemService.UpdateAsync(MaterialItemDto.Id.Value, MaterialItemDto);
                Aggregator.SendMessage($"设计物料：{MaterialItemDto.MtlNumber},{MaterialItemDto.Description} 修改成功！");
                MaterialItemDto.Id = Guid.Empty;
            }
            else
            {
                var dto = await _materialItemService.GetFirstOrDefaultByMtlNumberAsync(MaterialItemDto.MtlNumber);
                if (dto.Status)
                {
                    Aggregator.SendMessage($"请不要重复添加，设计物料：{MaterialItemDto.MtlNumber},{MaterialItemDto.Description}！");
                    return;
                }
                await _materialItemService.AddAsync(MaterialItemDto);
                Aggregator.SendMessage($"设计物料：{MaterialItemDto.MtlNumber},{MaterialItemDto.Description}添加成功！");
                MaterialItemDto.Id = Guid.Empty;
            }
            IsRightDrawerOpen = false;
            GetDataAsync();
        }
        catch (Exception e)
        {
            //发送错误报告
            Aggregator.SendMessage(e.Message);
        }
    }
    #endregion

    #region 打开CSV文件，更新列表
    private void OpenCsv()
    {
        var path = Path.Combine(Environment.CurrentDirectory, "MaterialItem.csv");
        var excelApp = new Application();
        excelApp.Workbooks.Open(path);
        excelApp.Visible=true;
    }

    private async void Update()
    {
        var path = Path.Combine(Environment.CurrentDirectory, "MaterialItem.csv");
        List<MaterialItemString> mtlItems;
        try
        {
            mtlItems= path.GetRecords<MaterialItemString>();
        }
        //StreamReader的异常
        catch (Exception e)
        {
            Aggregator.SendMessage($"请关闭Excel后再执行更新，{e.Message}");
            return;
        }
        var dtos = (await _materialItemService.GetAllAsync()).Result;
        foreach (var itemDto in mtlItems)
        {
            //判断编号是否相同
            var dto = dtos.FirstOrDefault(x => x.MtlNumber.Equals(itemDto.MtlNumber)) ?? new MaterialItemDto { Id = Guid.Empty };


            dto.MtlNumber=itemDto.MtlNumber;
            dto.Description=itemDto.Description;
            dto.EnDescription=itemDto.EnDescription;
            dto.Type=itemDto.Type;
            dto.Unit=itemDto.Unit.ToEnum<Unit_e>();
            dto.Length=itemDto.Length;
            dto.Width = itemDto.Width;
            dto.Height = itemDto.Height;
            dto.Material=itemDto.Material;
            dto.Hood=itemDto.Hood.ToBool();
            dto.HoodGroup = itemDto.HoodGroup.ToEnum<HoodGroup_e>();
            dto.Ceiling = itemDto.Ceiling.ToBool();
            dto.CeilingGroup = itemDto.CeilingGroup.ToEnum<CeilingGroup_e>();
            dto.CeilingRule = itemDto.CeilingRule.ToEnum<CeilingRule_e>();
            dto.Pst=itemDto.Pst.ToBool();
            dto.CalcRule=itemDto.CalcRule;
            dto.Pallet=itemDto.Pallet.ToBool();
            dto.NoLabel=itemDto.NoLabel.ToBool();
            dto.OneLabel=itemDto.OneLabel.ToBool();
            dto.Order = itemDto.Order.ToInt();
            if (dto.Id == Guid.Empty)
            {
                await _materialItemService.AddAsync(dto);
            }
            else
            {
                await _materialItemService.UpdateAsync(dto.Id.Value, dto);
            }
            break;
        }
        Aggregator.SendMessage("更新完毕！");
        GetDataAsync();
    }

    #endregion

    #region 筛选
    private void Filter()
    {
        FilterMaterialItemDtos.ReplaceRange(
            MaterialItemDtos.Where(x =>
                string.IsNullOrEmpty(Search)||
                (!string.IsNullOrEmpty(x.MtlNumber)&&x.MtlNumber.Contains(Search, StringComparison.OrdinalIgnoreCase))||
                (!string.IsNullOrEmpty(x.Description)&&x.Description.Contains(Search, StringComparison.OrdinalIgnoreCase))||
                (!string.IsNullOrEmpty(x.EnDescription)&&x.EnDescription!.Contains(Search, StringComparison.OrdinalIgnoreCase))));
    }
    #endregion

    #region 导航初始化
    private void GetEnumNames()
    {
        //初始化一些枚举值
        Units=Enum.GetNames(typeof(Unit_e));
        HoodGroups = Enum.GetNames(typeof(HoodGroup_e));
        CeilingGroups = Enum.GetNames(typeof(CeilingGroup_e));
        CeilingRules = Enum.GetNames(typeof(CeilingRule_e));
    }
    private async void GetDataAsync()
    {
        var result = await _materialItemService.GetAllAsync();
        if (!result.Status) return;
        MaterialItemDtos.ReplaceRange(result.Result);
        Filter();
    }
    public override void OnNavigatedTo(NavigationContext navigationContext)
    {
        base.OnNavigatedTo(navigationContext);
        GetEnumNames();
        GetDataAsync();
    }
    #endregion
}